﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.DynamicData;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Expressions;
using NotAClue.ComponentModel.DataAnnotations;
using NotAClue.Web;

namespace NotAClue.Web.DynamicData
{
    public static class PageTemplateExtensionMethods
    {
        // e.g. "~/DynamicData/PageTemplates/List.aspx"
        private const String extension = ".aspx";

        public static Dictionary<String, PageTemplate> PageTemplates { get; private set; }

        /// <summary>
        /// Maps unknown pages to page templates.
        /// </summary>
        /// <value>Page template mappings.</value>
        public static Dictionary<String, PageTemplate> PageTemplateMappings { get; set; }

        /// <summary>
        /// Initializes the <see cref="PageExtensionMethods"/> class.
        /// </summary>
        static PageTemplateExtensionMethods()
        {
            PageTemplateMappings = new Dictionary<string, PageTemplate>();
            PageTemplates = new Dictionary<string, PageTemplate>();
            foreach (PageTemplate item in Enum.GetValues(typeof(PageTemplate)))
            {
                PageTemplates.Add(item.ToString(), item);
            }
        }

        //public static T SetGridViewMetaTable<T>(this GridView gridView)
        //{
        //    return gridView.Page.FindControlRecursive<T>(gridView.DataSourceID);
        //}

        public static void SetGridViewMetaTable(this GridView gridView, MetaTable table, Boolean autoGenerateWhereClause = true)
        {
            gridView.SetMetaTable(table);
            var dataSource = gridView.Page.FindControlRecursive<EntityDataSource>(gridView.DataSourceID);
            //dataSource.EntityTypeFilter = table.EntityType.Name;
            dataSource.ContextTypeName = table.DataContextType.FullName;
            dataSource.EntitySetName = table.Name;
            //dataSource.ContextType = table.DataContextType;
            dataSource.AutoGenerateWhereClause = autoGenerateWhereClause;
            gridView.DataKeyNames = table.GetDataKeysNames();
        }

        /// <summary>
        /// Sets the table options.
        /// </summary>
        /// <param name="formView">The form view.</param>
        /// <param name="table">The table.</param>
        /// <remarks></remarks>
        public static void SetTableOptions(this FormView formView, MetaTable table, String controlId = "detailsTable")
        {
            var tableOptions = table.GetAttribute<TableOptionsAttribute>();
            if (tableOptions != null && !String.IsNullOrEmpty(tableOptions.FormCss))
            {
                var script = new StringBuilder();
                //<script type="text/javascript">
                //    $("#detailsTable").addClass("FullWidth");
                //</script>
                script.Append(String.Format("$(\"#{0}\").addClass(\"{1}\");", controlId, tableOptions.FormCss));
                formView.Page.AddStartupClientScript(table.Name + "TableOptions", script.ToString());
            }
        }

        /// <summary>
        /// Sets the initial sort order.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="table">The table.</param>
        /// <param name="queryExtender">The query extender.</param>
        public static void SetInitialSortOrder(this Page page, MetaTable table, QueryExtender queryExtender)
        {
            // set default sort
            if (!page.IsPostBack && table.SortColumn != null)
            {
                var order = new OrderByExpression()
                {
                    DataField = table.SortColumn.Name,
                    Direction = table.SortDescending ? SortDirection.Descending : SortDirection.Ascending,
                };
                queryExtender.Expressions.Add(order);
            }

        }

        /// <summary>
        /// Gets the page template from the page.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <returns></returns>
        public static PageTemplate GetPageTemplate(this Page page)
        {
            var path = page.AppRelativeVirtualPath;
            var pageName = path.Substring(path.LastIndexOf("/") + 1, path.Length - path.LastIndexOf("/") - extension.Length - 1);

            if (PageTemplates.Keys.Contains(pageName))
                return PageTemplates[pageName];

            if (PageTemplateMappings.Keys.Contains(pageName))
                return PageTemplateMappings[pageName];
            else
                return PageTemplate.Unknown;
        }

        //// get a data bindable list of permissions for the DDL
        //private static Dictionary<String, FormViewMode> modes = 
        //    new Dictionary<String, FormViewMode>()
        //    {
        //        {"Details",FormViewMode.ReadOnly},
        //        {"Edit",FormViewMode.Edit},
        //        {"Insert",FormViewMode.Insert},
        //    };

        //public static FormViewMode GetFromViewMode(this HttpRequest request)
        //{
        //    String path = request.Path;
        //    var qs = path.Substring(path.LastIndexOf("/") + 1, path.Length - (path.LastIndexOf("/") + 6));
        //    foreach (var item in modes)
        //    {
        //        if (qs == item.Key)
        //            return item.Value;
        //    }

        //    // default to readonly
        //    return FormViewMode.ReadOnly;
        //}
    }
}
